<?php
# file that will process and create timeline for user

# include of site functions
include_once $_SERVER["DOCUMENT_ROOT"].'Meet-n-go/php/includes.php'; 	// contains includes of all files with functions
session_start();					// starts session for current user
c_db_connect(); 					// connect to database

$get_line = ''; // will hold additional paramenters to add as get paramenters

// ensure go to correct date
if(!isset($_POST['date']) || empty($_POST['date'])) i_set_msg_err('Date empty');
else{
	$date = c_escape($_POST['date']); // escape before doing something with it
	
	if(strlen($date)!=10) i_set_msg_err('Incorrect date format');
	else{
		$year =  substr($date, 0, 4);
		$month = substr($date, 5, 2);
		$day =   substr($date, 8, 2);
		
		$get_line = "&year=$year&month=$month&day=$day";
	}
}

// if set new times was performed
if(isset($_POST['Set'])){

	$hours = c_get_free_times($date);
	
	$ci = 24;
	for($i=0;$i<$ci;$i++){
		if( !in_array(strval($i), $hours) && in_array(strval($i), $_POST['time'])){
			# need to add time
			
			$query = "INSERT INTO timetable(USER_ID, DATE, HOUR) VALUES (".$_SESSION['user_id'].", '$date', $i)";
			$result = c_db_query($query);
			if(!$result) i_set_msg_err('Error in database add');
		}
		elseif( in_array(strval($i), $hours) && !in_array(strval($i), $_POST['time'])){
			# need to remove time
			
			$user_id = $_SESSION['user_id'];
			
			$query = "DELETE FROM timetable WHERE USER_ID = $user_id AND DATE = '$date' AND HOUR = $i";
			$result = c_db_query($query);
			if(!$result) i_set_msg_err('Error in database delete');
		}
	}
}

c_db_disconnect(); 					// disconnect from database

# Where to go after processing
$page_id = I_SET_TIMELINE.$get_line;

# code that makes sure, this page is being redirected from afterwards
echo '<head><meta http-equiv="refresh" content="0; url=../../../index.php?id=' . $page_id . '" /></head>';


?>